package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.pojo.Chance;
import com.ktjy.pojo.Plan;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.IChanceService;
import com.ktjy.service.IPlanService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-01-15
 */
@Controller
@RequestMapping("/plan")
public class PlanController {
    Logger logger = LoggerFactory.getLogger(PlanController.class);

    @Autowired
    IChanceService iChanceService;
    @Autowired
    IPlanService iPlanService;

    /**
     * 列表展示
     *
     * @param chance
     * @param pageIndex
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(Chance chance,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       HttpSession session,
                       Model model) {
        try {
            //组装分页条件
            Page<Chance> page = new Page<>(pageIndex, pageSize);
            //组装过滤条件 动态sql
            QueryWrapper qw = new QueryWrapper();
            qw.in("chc_status", "2", "3", "4");
            if (chance.getChcCustName() != null && !chance.getChcCustName().equals("")) {
                qw.like("chc_cust_name", chance.getChcCustName());
            }
            if (chance.getChcLinkman() != null && !chance.getChcLinkman().equals("")) {
                qw.like("chc_linkman", chance.getChcLinkman());
            }
            if (chance.getChcTitle() != null && !chance.getChcTitle().equals("")) {
                qw.like("chc_title", chance.getChcTitle());
            }
            SysUser sysUser = (SysUser) session.getAttribute("loginUser");
            if (sysUser.getUsrRoleId() == 7) {//销售主管
                //只查自己创建的数据
                qw.eq("chc_create_id", sysUser.getUsrId());
            } else if (sysUser.getUsrRoleId() == 2) {//客户经理
                //只查指派给自己的数据
                qw.eq("chc_due_id", sysUser.getUsrId());
            }
            //调用分页方法
            IPage<Chance> pager = iChanceService.page(page, qw);
            model.addAttribute("pager", pager);

            //回显数据
            model.addAttribute("condition", chance);
        } catch (Exception e) {
            logger.error("PlanController 中的 list 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "plan/list";
    }

    /**
     * 跳转到新增页面
     *
     * @return
     */
    @GetMapping("/add")
    public String add(@RequestParam("id") Long id, Model model) {
        try {
            //根据销售机会ID，查询信息
            Chance chance = iChanceService.getById(id);
            model.addAttribute("chance", chance);

            //根据销售机会ID，查询开发计划
            QueryWrapper qw = new QueryWrapper();
            qw.eq("pla_chc_id", id);
            List<Plan> planList = iPlanService.list(qw);
            model.addAttribute("planList", planList);

            //显示当前时间
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            model.addAttribute("now", dtf.format(LocalDate.now()));

            return "plan/add";
        } catch (Exception e) {
            logger.error("PlanController 中的 add 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增操作
     *
     * @param plan
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public Object save(Plan plan) {
        Map<String, Object> map = new HashMap<>();
        try {
            plan.setPlaDate(LocalDateTime.now());
            boolean ok = iPlanService.save(plan);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 修改开发计划
     *
     * @param plan
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public Object update(Plan plan) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok = iPlanService.updateById(plan);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 删除开发计划
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok = iPlanService.removeById(id);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 跳转执行查看计划页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view")
    public String view(Long id, Model model) {
        try {
            //根据销售机会ID，查询信息
            Chance chance = iChanceService.getById(id);
            model.addAttribute("chance", chance);

            //根据销售机会ID，查询开发计划
            QueryWrapper qw = new QueryWrapper();
            qw.eq("pla_chc_id", id);
            List<Plan> planList = iPlanService.list(qw);
            model.addAttribute("planList", planList);
        } catch (Exception e) {
            logger.error("PlanController 中的 view 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "plan/view";
    }

    /**
     * 跳转添加执行结果页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/addPlanResult")
    public String addPlanResult(Long id, Model model) {
        try {
            //根据销售机会ID，查询信息
            Chance chance = iChanceService.getById(id);
            model.addAttribute("chance", chance);
            //根据销售机会ID，查询开发计划
            QueryWrapper qw = new QueryWrapper();
            qw.eq("pla_chc_id", id);
            List<Plan> planList = iPlanService.list(qw);
            model.addAttribute("planList", planList);
        } catch (Exception e) {
            logger.error("PlanController 中的 addPlanResult 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "plan/result";
    }

    /**
     * 保存执行效果
     *
     * @param plan
     * @return
     */
    @RequestMapping("/savePlanResult")
    @ResponseBody
    public Object savePlanResult(Plan plan) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok=iPlanService.updateById(plan);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 处理销售机会，开发成功操作
     * @param id
     * @return
     */
    @RequestMapping("/success")
    @ResponseBody
    public Object success(Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok=iChanceService.successChance(id);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }

    /**
     * 处理销售机会，开发失败操作
     * @param id
     * @return
     */
    @RequestMapping("/fail")
    @ResponseBody
    public Object fail(Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean ok=iChanceService.failChance(id);
            if (ok) {
                map.put("delResult", true);
            } else {
                map.put("delResult", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", false);
        }
        return map;
    }
}
